package com.baidu.encrypt.controller;

import com.baidu.encrypt.common.utils.MinioEncryptService;
import com.baidu.sggc.audit.extend.AuditExtendContext;
import com.baidu.sggc.audit.extend.FileMessage;
import com.baidu.sggc.core.common.R;
import com.baidu.sggc.entity.vo.FsVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/fs")
@RequiredArgsConstructor
public class FileUploadController {

    @Autowired
    private MinioEncryptService minioEncryptService; // 使用加密版 MinIO 服务

    @Operation(summary = "上传加密文件", description = "上传文件并在存储前加密")
    @PostMapping(value = "/sample/upload", headers = "content-type=multipart/form-data")
    public R<FsVo> uploadFile(@RequestParam("file") MultipartFile file) {
        System.out.println("/fs/sample/upload" + ": " + LocalDateTime.now());

        String fileName = file.getOriginalFilename();
        if (fileName == null || !fileName.toLowerCase().endsWith(".txt")) {
            return R.err("只能上传.txt格式文件");
        }

        // 审计扩展字段：FileMessage
        FileMessage msg = new FileMessage();
        Map<String, List<String>> fileMap = new HashMap<>();
        fileMap.put("模型目录", Collections.singletonList(fileName));
        msg.setFileInfo(fileMap);
        AuditExtendContext.setExtendData(toMap(msg));

        // 调用加密上传
        FsVo fsVo = minioEncryptService.uploadEncrypted(file);
        return R.ok(fsVo);
    }

    @Operation(summary = "下载并解密文件", description = "从MinIO下载文件并解密")
    @GetMapping("/sample/download")
    public void downloadFile(@RequestParam("objectName") String objectName, HttpServletResponse response) {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"decrypted_" + objectName + "\"");
        try {
            minioEncryptService.downloadAndDecrypt(objectName, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("下载文件失败", e);
        }
    }


    private Map<String, Object> toMap(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.convertValue(obj, Map.class);
    }
}
